package com.example.sangong.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sangong.dao.AttachmentDao;
import com.example.sangong.entity.Attachment;
import com.example.sangong.req.attachment.AttachmentUrlReq;
import com.example.sangong.resp.AttachmentUploadRsp;
import com.example.sangong.resp.AttachmentUrlResp;
import com.example.sangong.service.AttachmentService;
import com.example.sangong.utils.MinioUtils;
import com.example.sangong.utils.MyStreamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentDao, Attachment> implements AttachmentService {

    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private AttachmentDao attachmentDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AttachmentUploadRsp uploadFile(MultipartFile file) {
        Attachment attachment = minioUtils.uploadFile(file);
        attachmentDao.insert(attachment);
        return AttachmentUploadRsp.convert(attachment);
    }

    @Transactional(rollbackFor = Exception.class)
    public List<AttachmentUploadRsp> batchUpload(List<MultipartFile> files) {
        List<Attachment> attachments = minioUtils.batchUploadFile(files);
        saveBatch(attachments);
        return MyStreamUtils.cosList(attachments, AttachmentUploadRsp::convert);
    }

    @Override
    public List<AttachmentUrlResp> getAttachmentUrls(AttachmentUrlReq attachmentUrlReq) {

        return MyStreamUtils.cosList(attachmentDao.selectBatchIds(attachmentUrlReq.getAttachmentIds()), e -> AttachmentUrlResp.convert(e, minioUtils.getAccessServer()));
    }
}
